<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <searchBar :show-channel-id="false" :show-server-id="false" @transferFilter="handleFilter" />
      <el-button v-if="checkPermission(permissionRoles.channel_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加渠道</el-button>
    </div>
    <div style="min-height: 725px;">
      <el-table ref="table" v-loading="listLoading" :data="list" border>
        <el-table-column prop="cid" align="center" min-width="80" label="渠道ID" fixed></el-table-column>
        <el-table-column prop="name" align="center" min-width="100" label="渠道名称"></el-table-column>
        <el-table-column prop="remark" align="center" label="备注"></el-table-column>
        <el-table-column prop="srname" align="center" min-width="150" label="指定大区"></el-table-column>
        <el-table-column prop="login_cid" align="center" label="映射渠道"></el-table-column>
        <el-table-column prop="sdk_alias" align="center" label="重用SDK渠道()"></el-table-column>
        <el-table-column prop="group_name" align="center" label="所属分组"></el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="{row}">
            <el-tag v-if="row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">不可用</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否GM">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_gm === 1" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否开启支付">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_open_pay === 1" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button v-if="checkPermission(permissionRoles.channel_edit)" type="text" size="small" @click="handleEdit(scope)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
        <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
          <el-form-item label="渠道ID" prop="cid">
            <el-input v-model="dataForm.cid" :disabled="cidDisabled" class="defaut-input" placeholder="填写渠道ID" />
          </el-form-item>
          <el-form-item label="渠道名称" prop="name">
            <el-input v-model="dataForm.name" class="defaut-input" placeholder="填写渠道名称" />
          </el-form-item>
          <el-form-item label="指定大区" prop="srid">
            <el-select v-model="dataForm.srid" multiple filterable class="defaut-input" clearable>
              <el-option
                v-for="item in serverRegionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属分组" prop="group">
            <el-select v-model="dataForm.group" multiple filterable class="defaut-input" clearable>
              <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="映射渠道ID" prop="login_cid">
            <el-input v-model="dataForm.login_cid" class="defaut-input" placeholder="填写映射渠道ID" />
          </el-form-item>
          <el-form-item label="重用SDK渠道" prop="sdk_alias">
            <el-input v-model="dataForm.sdk_alias" class="defaut-input" placeholder="填写重用SDK渠道ID" />
          </el-form-item> -->
          <el-form-item label="映射渠道ID" prop="login_cid">
            <el-select v-model="dataForm.login_cid" filterable class="defaut-input" clearable>
              <el-option
                v-for="(value, index) in sdkList"
                :key="index"
                :label="value"
                :value="value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="重用SDK渠道" prop="sdk_alias">
            <el-select v-model="dataForm.sdk_alias" filterable class="defaut-input" clearable>
              <el-option
                v-for="(value, index) in sdkList"
                :key="index"
                :label="value"
                :value="value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" class="defaut-input" placeholder="备注" />
          </el-form-item>
          <el-form-item label="是否可用">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">不可用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否开启支付">
            <el-radio-group v-model="dataForm.is_open_pay">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否GM">
            <el-radio-group v-model="dataForm.is_gm">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="tr">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmSubmit()">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { objectMerge, deepClone } from '@/utils'
import { getChannelGroupConfigList, getChannelList, handleChannel, getServerRegionList, getSDKList } from '@/api/ops'
import Pagination from '@/components/Pagination'
import SearchBar from '@/components/SearchBar'

const defaultItem = {
  id: '',
  cid: '',
  login_cid: '',
  name: '',
  status: 1,
  is_gm: 0,
  is_open_pay: 1,
  sdk_alias: '',
  srid: [],
  remark: ''
}
export default {
  name: 'Channel',
  components: { SearchBar, Pagination },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      total: 0,
      sdkList: [],
      listQuery: {
        page: 1,
        limit: 100
      },
      searchBarQuery: {},
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      rules: {
        cid: [{ required: true, message: '请填写渠道ID', trigger: 'blur' }],
        name: [{ required: true, message: '请填写渠道名', trigger: 'blur' }],
        srid: [{ required: true, message: '请选择至少一个大区', trigger: 'blur' }]
      },
      list: [],
      serverRegionList: [],
      groupList: [],
      dialogVisible: false,
      cidDisabled: false,
      dialogType: 'new',
      textMap: {
        edit: '编辑',
        new: '新增'
      }
    }
  },
  created() {
    console.log(this.dataForm.is_open_pay)
    this.init()
    this.getServerRegionList()
    this.getChannelGroupConfigList()
  },
  methods: {
    checkPermission,
    init() {
      this.getList()
      this.getSDKList()
    },
    async getSDKList() {
      const res = await getSDKList()
      this.sdkList = res.data
    },
    async getServerRegionList() {
      const res = await getServerRegionList()
      this.serverRegionList = res.data
    },
    async getChannelGroupConfigList() {
      const res = await getChannelGroupConfigList()
      this.groupList = res.data
    },
    handleFilter(query) {
      this.searchBarQuery = query
      this.getList()
    },
    async getList() {
      const query = objectMerge(this.searchBarQuery, this.listQuery)
      this.listLoading = true
      const res = await getChannelList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.cidDisabled = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUnique(list) {
      console.log(list)
      const newList = [...new Set(
        list.filter(item => item.trim() !== '' && item !== null && item !== undefined)
      )]
      newList.push('')
      return newList
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.cidDisabled = true
      const srids = scope.row.srid
      const sdkList = JSON.parse(JSON.stringify(this.sdkList))
      sdkList.push(scope.row.login_cid)
      sdkList.push(scope.row.sdk_alias)
      this.sdkList = this.handleUnique(sdkList)
      if (srids.length > 0) {
        for (let i = 0; i <= srids.length; i++) {
          if (scope.row.srid[i] === '') {
            scope.row.srid[i] = null
            break
          }
          if (typeof (scope.row.srid[i]) === 'undefined') {
            break
          }
          scope.row.srid[i] = Number(scope.row.srid[i])
        }
      }
      console.log(scope.row.srid)
      this.dataForm = deepClone(scope.row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCid() {
      if (this.dataForm.login_cid === '') this.dataForm.login_cid = this.dataForm.cid
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogType === 'edit'
          handleChannel(this.dataForm).then(response => {
            if (response.status) {
              this.getList()
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.el-table {
  font-size: 14px;
}
.el-table td, .el-table th {
  padding: 10px 0 !important;
}
.el-table th>.cell {
  padding-left: 10px;
  padding-right: 10px;
}

.el-table td {
  text-align: left !important;
}
</style>
